package com.tangding.interceptors;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import com.tangding.common.tools.ErrorConstants;
import com.tangding.service.entity.user.User;

/**
 * @description 权限控制
 *
 * @author Ranger
 * @version 2017年1月3日_下午2:26:51
 *
 */
public class AuthInterceptor extends BaseInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			User user = (User) request.getSession().getAttribute("currentUser");
			if (user != null) {
				Boolean enable = user.isEnable();
				if (enable != null && !enable) {
					sendErrorMsgView(response, ErrorConstants.ERR_LOCK_ACCOUNT, "redirect:/login");
					return false;
				}
				Date start = user.getEnableStart();
				Date end = user.getEnableEnd();
				Date now = new Date();
				if (start != null) {//开始时间不为空
					if (start.getTime() > now.getTime()) {// 开始启用时间大于当前时间
						sendErrorMsgView(response, ErrorConstants.ERR_NOT_ACTIVE, "redirect:/login");
						return false;
					}
				}
				
				if (end != null) {
					if (end.getTime() < now.getTime()) {// 结束启用时间小于当前时间
						sendErrorMsgView(response, ErrorConstants.ERR_ACCOUNT_OVERDUE, "redirect:/login");
						return false;
					}
				}
			}
			
		}
		return defaultAuth;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 默认是否进行验证权限
	 */
	private boolean defaultAuth = true;

	public boolean isDefaultAuth() {
		return defaultAuth;
	}

	public void setDefaultAuth(boolean defaultAuth) {
		this.defaultAuth = defaultAuth;
	}

}
